package server;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * selector
 */
@Slf4j
public class MyServer {


    public static void main(String[] args) {
        Thread.currentThread().setName("boss");
        //创建selector，管理多个channel
        try(Selector boss = Selector.open();
            ServerSocketChannel serverSocket = ServerSocketChannel.open()) {
            serverSocket.configureBlocking(false);//accept不阻塞
            //注册 channel注册到selector
            //SelectionKey 事件发生后，通过它可以知道事件和哪个channel的事件
            //事件发送后要么处理，要么取消，不能不理
            //read wirte accept connect事件
            SelectionKey bossKey = serverSocket.register(boss, 0, null);
            //key 只关注accept事件
            bossKey.interestOps(SelectionKey.OP_ACCEPT);
            log.info("register key:{}", bossKey);
            //绑定端口
            serverSocket.bind(new InetSocketAddress(9099));
            log.info("服务器正在启动......");

            //创建固定数量worker
            Worker[] workers = new Worker[3];
            for (int i = 0; i < workers.length; i++) {
                workers[i] = new Worker("worker-" + i);
            }
            AtomicInteger index = new AtomicInteger();
            while (true) {
                //select方法，没有事件发送，线程阻塞，有事件，线程才会恢复运行
                boss.select();
                //处理事件，selectedkeys 内部包含了所有发生的事件
                Iterator<SelectionKey> it = boss.selectedKeys().iterator();
                while (it.hasNext()) {

                    SelectionKey key = it.next();
                    it.remove();//处理完的key需要删除，在selectedKeys中
                    log.info("now_key: {}", key);

                    //区分事件
                    if (key.isAcceptable()) {//accept事件
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        SocketChannel sc = channel.accept();
                        sc.configureBlocking(false);//设置非阻塞
                        //round robin
                        workers[index.getAndIncrement() % workers.length].register(sc);
                        log.info("accept {}", sc);
                    }

//                    else if (key.isReadable()) {//read事件
//                        try {
//                            SocketChannel channel = (SocketChannel) key.channel();
//                            //获取selectionKey 上关联的附件
//                            ByteBuffer byteBuffer_attachment = (ByteBuffer) key.attachment();
//                            int read = channel.read(byteBuffer_attachment);//正常断开，read方法返回值为-1
//                            if (read == -1) {
//                                logger.info("已断开，取消 {}", key);
//                                key.cancel();
//                            }else {
//                                byteBuffer_attachment.flip();
//                                logger.info("read {}", Charset.defaultCharset().decode(byteBuffer_attachment));
//                            }
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                            key.cancel();//客户端断开了，取消key，从selector的keys集合中真正删除key
//                        }
//                    }

                }
            }
        }catch (IOException e) {
            log.error("有错误发生：", e);
        }
    }

    /**
     * 监测读写事件
     */
    static class Worker implements Runnable {
        private Thread thread;
        private Selector workerSelector;
        private String name;

        private volatile boolean start = false;//还未初始化
        ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }

        /**
         * 初始化线程，和selector
         * 执行一遍
         * @throws IOException
         */
        public void register(SocketChannel sc) throws IOException {
            if (!start) {
                thread = new Thread(this, name);
                workerSelector = Selector.open();
                start = true;

                thread.start();
            }
            queue.add(()->{
                try {
                    sc.register(workerSelector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            workerSelector.wakeup();//唤醒
        }

        @Override
        public void run() {
            while (true) {
                try {
                    workerSelector.select();//会阻塞

                    Runnable task = queue.poll();
                    if (task != null) {
                        task.run();//执行注册代码
                    }
                    Iterator<SelectionKey> it = workerSelector.selectedKeys().iterator();
                    while (it.hasNext()) {
                        SelectionKey key = it.next();
                        it.remove();
                        if (key.isReadable()) {

                            ByteBuffer allocate = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel)key.channel();
                            channel.read(allocate);
                            allocate.flip();
                            System.out.println(allocate);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
